import datetime

import django_filters
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from loguru import logger
from rest_framework.filters import BaseFilterBackend

from apps.prescription.models import Prescription, Drug


# 药方
class PrescriptionFilter(django_filters.rest_framework.FilterSet):
    # 处方编号
    OrderNum = django_filters.CharFilter(lookup_expr="icontains")
    # 发药日期时间
    OrderDtm = django_filters.CharFilter(method="filter_OrderDtm")
    # 根据是否有效
    is_active = django_filters.BooleanFilter(field_name="is_active",lookup_expr="exact")
    # 处方状态
    OrderStatus = django_filters.CharFilter(lookup_expr="exact")
    # 处方类型
    OrderType = django_filters.CharFilter(lookup_expr="exact")

    user_id = django_filters.CharFilter(method="filter_user_id")

    def filter_OrderDtm(self, queryset, name, value):
        """根据发药具体日期时间段筛选"""
        return queryset.filter(submit_datetime__range=value.split(","))

    def filter_user_id(self, queryset, name, value):
        """根据发药具体日期时间段筛选"""
        return queryset.filter(user__id=value)

    class Meta:
        model = Prescription
        fields = [
            "id",
            "OrderNum",
            "OrderDtm",
            "OrderType",
            "OrderStatus",
            "is_active"
        ]


# 药品筛选
class DrugFilter(django_filters.rest_framework.FilterSet):
    # 处方编号
    OrderNum = django_filters.CharFilter(lookup_expr="icontains")
    # 发药日期时间
    OrderDtm = django_filters.CharFilter(method="filter_OrderDtm")
    # 根据是否有效
    is_active = django_filters.BooleanFilter(field_name="is_active",lookup_expr="exact")
    # 处方状态
    OrderStatus = django_filters.CharFilter(lookup_expr="exact")
    # prescription = django_filters.CharFilter(lookup_expr="exact")
    prescrption_id = django_filters.CharFilter(method="filter_prescrption_id")


    def filter_prescrption_id(self, queryset, name, value):
        """根据发药具体日期时间段筛选"""
        return queryset.filter(prescrption__id=value)

    def filter_OrderDtm(self, queryset, name, value):
        """根据发药具体日期时间段筛选"""
        return queryset.filter(submit_datetime__range=value.split(","))

    class Meta:
        model = Drug
        fields = "__all__"
        # fields = [
        #     "id",
        #     "OrderNum",
        #     "OrderDtm",
        # ]
